<template>
  <div>
    <el-upload
      :action="fileUrl"
      list-type="picture-card"
      :limit="3"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :on-error="handleError"
      :on-exceed="handleExceed"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import { fileUrl, staticImgUrl } from '@/url'
export default {
  name: 'UploadImageList',
  props: {
    url: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      fileUrl: fileUrl,
      staticImgUrl: staticImgUrl,
      pictureUrl: '',
      loadingFlag: false,
      fileList: [],
      dialogImageUrl: '',
      dialogVisible: false
    }
  },
  watch: {
    url: {
      immediate: true,
      handler: function(newval, oldval) {
        if (newval !== oldval) {
          this.pictureUrl = newval
        }
      }
    }
  },
  created() {
    if (this.url) this.pictureUrl = this.url
  },
  methods: {
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleError() {
      this.loadingFlag = false
    },
    handleAvatarSuccess(res, file) {
      this.$emit('setUrl', res.data.url)
    },
    handleExceed() {
      this.$message.info('最多只能上传三张图片')
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt6M = file.size / 1024 / 1024 < 6
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
        this.loadingFlag = false
      }
      if (!isLt6M) {
        this.$message.error('上传头像图片大小不能超过 6MB!')
        this.loadingFlag = false
      }
      return isJPG && isLt6M
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
